package 剑指Offer._6170;

/**
 * @author yzh
 * @version 1.0
 * @date 2021/12/23 13:39
 * 把字符串转换成整数
 * 算法：字符串
 */
public class _67 {
    public static void main(String[] args) {
        System.out.println(Integer.MAX_VALUE % 10);
        System.out.println(Integer.MIN_VALUE % 10);
        System.out.println(new _67().strToInt(""));
    }

    public int strToInt(String str) {
        int ans = 0, len = str.length();
        final char[] chars = str.toCharArray();
        int idx = 0;
        while (idx < len && chars[idx] == ' ') ++idx;
        if (idx == len) return ans;
        int flag = 1;
        if (chars[idx] == '+') ++idx;
        else if (chars[idx] == '-') {
            flag = -1;
            ++idx;
        }
        int max = Integer.MAX_VALUE / 10, min = Integer.MIN_VALUE / 10;
        for (; idx < len; idx++) {
            char c = chars[idx];
            if (c < '0' || c > '9') break;
            if (ans > max || (ans == max && (c - '0') > 7)) return Integer.MAX_VALUE;
            if (ans < min || (ans == min && (c - '0') > 8)) return Integer.MIN_VALUE;
            ans = ans * 10 + (c - '0') * flag;
        }
        return ans;
    }

}
